package redora.client.model;

import com.google.gwt.gen2.table.client.FixedWidthFlexTable;
import com.google.gwt.gen2.table.client.FixedWidthGrid;
import com.google.gwt.gen2.table.client.ScrollTable;
import com.google.gwt.gen2.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.gen2.table.override.client.FlexTable.FlexCellFormatter;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.LazyPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class AttributeFieldsView extends LazyPanel {

    private ScrollTable fieldScrollTable = null;
    private ScrollTable businessRuleScrollTable = null;
    String baseUrl = URL.encode("../redoraOperations.do?_operationType=getFieldsByObjectName");
    VerticalPanel root = new VerticalPanel();
    String objectName = "";
    JSONObject object = new JSONObject();

    public AttributeFieldsView(String modelName) {
        this.objectName = modelName;
    }

    @Override
    protected Widget createWidget() {

        fieldScrollTable = createFieldTable();

        businessRuleScrollTable = createBusinessRuleTable();

        createDataList();

        root.setSize("100%", "100%");

        root.add(fieldScrollTable);

        root.add(businessRuleScrollTable);

        return root;
    }

    /**
     * Get the User Data List.
     * 
     */
    private void createDataList() {
        String _url = URL.encode(baseUrl + "&objectName=" + objectName);
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
        builder.setCallback(new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                Window.alert("createDataList failed!");
            }

            public void onResponseReceived(Request request, Response response) {
                JSONObject object = JSONParser.parse(response.getText()).isObject().get("response").isObject().get("data").isObject();
                JSONArray fieldArray = object.get("field").isArray();
                JSONArray businessRuleArray = object.get("businessRule").isArray();
                copyFieldValue(fieldScrollTable.getDataTable(), fieldArray);
                copyBusinessRuleValue(businessRuleScrollTable.getDataTable(), businessRuleArray);
            }
        });
        try {
            builder.send();
        } catch (RequestException e) {
            e.printStackTrace();
        }
    }

    private ScrollTable createFieldTable() {

        FixedWidthFlexTable footerTable = new FixedWidthFlexTable();

        FixedWidthFlexTable headerTable = new FixedWidthFlexTable();
        FlexCellFormatter formatter = headerTable.getFlexCellFormatter();
        // Level 1 headers
        headerTable.setHTML(0, 0, "<b>Fields</b>");
        formatter.setColSpan(0, 0, 9);
        formatter.setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT);

        // Level 2 headers
        headerTable.setHTML(1, 0, "Name or class");
        formatter.setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER);

        headerTable.setHTML(1, 1, "Type");
        formatter.setHorizontalAlignment(1, 1, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 2, "Not null");
        formatter.setHorizontalAlignment(1, 2, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 3, "Default");
        formatter.setHorizontalAlignment(1, 3, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 4, "Max length");
        formatter.setHorizontalAlignment(1, 4, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 5, "Regulare expression");
        formatter.setHorizontalAlignment(1, 5, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 6, "Finder");
        formatter.setHorizontalAlignment(1, 6, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 7, "Lazy");
        formatter.setHorizontalAlignment(1, 7, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 8, "List");
        formatter.setHorizontalAlignment(1, 8, HasHorizontalAlignment.ALIGN_CENTER);

        final FixedWidthGrid dataTable = new FixedWidthGrid();
        dataTable.setSelectionEnabled(false);
        dataTable.setSelectionPolicy(SelectionPolicy.ONE_ROW);

        dataTable.resizeColumns(9);

        // Combine the components into a ScrollTable
        final ScrollTable scrollTable = new ScrollTable(dataTable, headerTable);
        scrollTable.setFooterTable(footerTable);

        // Set some options in the scroll table
        // scrollTable.setSortingEnabled(true);
        scrollTable.setResizePolicy(ScrollTable.ResizePolicy.FILL_WIDTH);
        scrollTable.setSize("100%", "300");

        // Setup some default widths
        scrollTable.setMaximumColumnWidth(0, 200);
        scrollTable.setPreferredColumnWidth(0, 150);
        scrollTable.setMinimumColumnWidth(0, 150);

        scrollTable.setMaximumColumnWidth(1, 200);
        scrollTable.setPreferredColumnWidth(1, 150);
        scrollTable.setMinimumColumnWidth(1, 150);
        
        scrollTable.setMaximumColumnWidth(2, 100);
        scrollTable.setPreferredColumnWidth(2, 100);
        scrollTable.setMinimumColumnWidth(2, 100);

        return scrollTable;
    }

    private ScrollTable createBusinessRuleTable() {

        FixedWidthFlexTable footerTable = new FixedWidthFlexTable();

        FixedWidthFlexTable headerTable = new FixedWidthFlexTable();
        FlexCellFormatter formatter = headerTable.getFlexCellFormatter();
        // Level 1 headers
        headerTable.setHTML(0, 0, "<b>Business Rules</b>");
        formatter.setColSpan(0, 0, 3);
        formatter.setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT);

        // Level 2 headers
        headerTable.setHTML(1, 0, "Number");
        formatter.setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 1, "Attributes");
        formatter.setHorizontalAlignment(1, 1, HasHorizontalAlignment.ALIGN_CENTER);
        headerTable.setHTML(1, 2, "Description");
        formatter.setHorizontalAlignment(1, 2, HasHorizontalAlignment.ALIGN_CENTER);

        final FixedWidthGrid dataTable = new FixedWidthGrid();
        dataTable.setSelectionEnabled(false);
        dataTable.setSelectionPolicy(SelectionPolicy.ONE_ROW);

        dataTable.resizeColumns(3);

        // Combine the components into a ScrollTable
        final ScrollTable scrollTable = new ScrollTable(dataTable, headerTable);
        scrollTable.setFooterTable(footerTable);

        // Set some options in the scroll table
        // scrollTable.setSortingEnabled(true);
        scrollTable.setResizePolicy(ScrollTable.ResizePolicy.FILL_WIDTH);
        scrollTable.setSize("100%", "300");

        // Setup some default widths
        scrollTable.setMaximumColumnWidth(0, 100);
        scrollTable.setPreferredColumnWidth(0, 75);
        scrollTable.setMinimumColumnWidth(0, 50);

        scrollTable.setMaximumColumnWidth(1, 200);
        scrollTable.setPreferredColumnWidth(1, 150);
        scrollTable.setMinimumColumnWidth(1, 100);

        return scrollTable;
    }

    private void copyBusinessRuleValue(FixedWidthGrid dataTable, JSONArray array) {
        dataTable.resizeRows(array.size());
        for (int i = 0; i < array.size(); i++) {
            JSONObject value = array.get(i).isObject();
            if (value.get("number") != null
                && !value.get("number").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 0, value.get("number").isString().stringValue());
            }
            if (value.get("attributes") != null
                && !value.get("attributes").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 1, value.get("attributes").isString().stringValue());
            }
            if (value.get("javadoc") != null
                && !value.get("javadoc").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 2, value.get("javadoc").isString().stringValue());
            }
        }
    }

    private void copyFieldValue(FixedWidthGrid dataTable, JSONArray array) {
        dataTable.resizeRows(array.size());
        for (int i = 0; i < array.size(); i++) {
            JSONObject value = array.get(i).isObject();
            if (value.get("field_name") != null
                && !value.get("field_name").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 0, value.get("field_name").isString().stringValue());
            }
            if (value.get("field_type") != null
                && !value.get("field_type").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 1, value.get("field_type").isString().stringValue());
            }
            if (value.get("not_null") != null
                && !value.get("not_null").toString().equalsIgnoreCase("null")) {
                CheckBox box = new CheckBox();
                box.setValue(Boolean.valueOf(value.get("not_null").isString().stringValue()));
                box.setEnabled(false);
                dataTable.setWidget(i, 2, box);
            }
            if (value.get("default") != null
                && !value.get("default").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 3, value.get("default").isString().stringValue());
            }
            if (value.get("maxlength") != null
                && !value.get("maxlength").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 4, value.get("maxlength").isString().stringValue());
            }
            if (value.get("regexp") != null
                && !value.get("regexp").toString().equalsIgnoreCase("null")) {
                dataTable.setText(i, 5, value.get("regexp").isString().stringValue());
            }
            if (value.get("finder") != null
                && !value.get("finder").toString().equalsIgnoreCase("null")) {
                CheckBox box = new CheckBox();
                box.setValue(Boolean.valueOf(value.get("finder").isString().stringValue()));
                box.setEnabled(false);
                dataTable.setWidget(i, 6, box);
            }
            if (value.get("lazy") != null && !value.get("lazy").toString().equalsIgnoreCase("null")) {
                CheckBox box = new CheckBox();
                box.setValue(Boolean.valueOf(value.get("lazy").isString().stringValue()));
                box.setEnabled(false);
                dataTable.setWidget(i, 7, box);
            }
            if (value.get("list") != null
                && !value.get("list").toString().equalsIgnoreCase("null")) {
                CheckBox box = new CheckBox();
                box.setValue(Boolean.valueOf(value.get("list").isString().stringValue()));
                box.setEnabled(false);
                dataTable.setWidget(i, 8, box);
            }
        }
    }
}
